package com.tgjorgoski.spellcheck.highlight;

import javax.swing.text.*;

/**
 * 
 * @author Tanasije Gjorgoski <tanas@ameritege.com>
 */
public class HighlightUtil {

	/**
	 * Adds highlights in given text Component using the data from the
	 * specific highlighter
	 * 
	 * @param textComp
	 * @param highlighter
	 */
	 public static void highlight(JTextComponent textComp, NodesHighlighter highlighter) {
		 // First remove all old highlights
		 removeHighlights(textComp, highlighter);
		 Highlighter.HighlightPainter painter = highlighter.getHighlighterPainter();
		 try {
			 Highlighter hilite = textComp.getHighlighter();
			 Document doc = textComp.getDocument();
			 NodeSectionsIterator itt = highlighter.getNodeSectionsIterator(doc);
			 for (;itt.hasNext();) {
			 	NodeSection ns = itt.next();
				 // Create highlighter using private painter and apply around pattern
				 hilite.addHighlight(ns.getSectionStart(), ns.getSectionEnd(), painter);
			 }
		 } catch (BadLocationException e) {
		 	e.printStackTrace();
		 }
	 }
    

	 /**
	 * Removes highlights on the text component that belong to the given highlighter
	 * @param textComp
	 * @param highlighter
	 */
	public static void removeHighlights(JTextComponent textComp, NodesHighlighter highlighter) {
		 Highlighter hilite = textComp.getHighlighter();
		 Highlighter.Highlight[] hilites = hilite.getHighlights();
		 Highlighter.HighlightPainter painter = highlighter.getHighlighterPainter();
		 
		 for (int i=0; i<hilites.length; i++) {
			 if (hilites[i].getPainter()==painter) {
				 hilite.removeHighlight(hilites[i]);
			 }
		 }
	 }

	 /**
	 * Removes highlights on the text component that belong to the given highlighter
	 * @param textComp
	 * @param highlighter
	 */
	public static void removeAllHighlights(JTextComponent textComp) {
		 Highlighter hilite = textComp.getHighlighter();
		 Highlighter.Highlight[] hilites = hilite.getHighlights();
		 
		 for (int i=0; i<hilites.length; i++) {
			 hilite.removeHighlight(hilites[i]);
		 }
	 }

}

